<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      v-show="showSearch"
      :inline="true"
      label-width="84px"
    >
      <el-form-item label="授权码" prop="key">
        <el-input v-model.trim="queryParams.key" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="用户名" prop="userName">
        <el-input v-model.trim="queryParams.userName" placeholder="请输入"></el-input>
      </el-form-item>

      <el-form-item label="创建时间">
        <el-date-picker
          v-model="queryParams.date"
          type="daterange"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5" v-if="ids.length > 0">
        <el-button type="danger" plain icon="Delete" @click="batchDelete">批量删除</el-button>
      </el-col>

      <el-col :span="1.5" v-if="ids.length > 0">
        <el-button type="primary" plain @click="batchUpdate">批量更新</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" plain @click="exportAll">导出筛选数据</el-button>
      </el-col>
      <el-col :span="9">
        <el-alert title="关联账号池数据点击展开可查看频道下所有token快速剩余时间" type="warning" />
      </el-col>
      <right-toolbar :search="false" v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 表格数据 -->
    <el-table
      ref="tableRef"
      v-loading="loading"
      row-key="id"
      lazy
      :data="list"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" :align="`center`" />

      <el-table-column label="授权码" prop="key" width="340"></el-table-column>
      <el-table-column label="是否消费" prop="isConsumption" width="200">
        <template #default="{row}">
          <el-tag size="mini" :type="{0: '', 1: 'warning'}[row.isConsumption]">{{ row.isConsumption ? '已消费' : '未消费'}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="消费时间" prop="consumptionTime" width="200"></el-table-column>
      <el-table-column label="快速模式总次数" prop="fastMaxCount" width="200"></el-table-column>
      <el-table-column label="relax模式总次数" prop="relaxMaxCount" width="200"></el-table-column>
      <el-table-column label="关联用户名" prop="userName" width="200"></el-table-column>
      <el-table-column label="菜单id" prop="guildId" width="180"></el-table-column>
      <el-table-column label="频道id" prop="channelId" width="180"></el-table-column>
      <el-table-column label="创建时间" prop="createTime" width="180"></el-table-column>

      <el-table-column label="备注" prop="remark" width="160"></el-table-column>
      <el-table-column
        label="操作"
        :align="`center`"
        fixed="right"
        class-name="small-padding fixed-width"
        width="200"
      >
        <!-- 未结算才能启用 -->
        <template #default="{ row }">
          <el-tooltip content="修改" placement="top">
            <el-button link type="primary" icon="Edit" @click="handleUpdate(row)"></el-button>
          </el-tooltip>
          <el-tooltip content="删除" placement="top">
            <el-button link type="danger" icon="Delete" @click="deleteHandler(row)"></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>

    <Pagination
      v-show="total > 0"
      :total="total"
      v-model:page="pagination.current"
      v-model:limit="pagination.size"
      @pagination="getList"
    />

    <!-- 添加或修改角色配置对话框 -->
    <el-dialog :title="title" v-model="open" width="700px" append-to-body>
      <el-form ref="roleRef" :inline="false" :model="form" :disabled="form.isConsumption" :rules="rules" label-width="140px">
        <el-form-item label="授权码" prop="key">
          <el-input disabled v-model.trim="form.key" placeholder="请输入授权码" />
        </el-form-item>
        <!-- 套餐框 -->
        <template v-if="!isEdit">
          <el-form-item label="选择套餐" prop="type">
            <el-select v-model="form.meal" @change="mealChangeHandler">
              <el-option
                v-for="(item, index) in mealList"
                :key="index"
                :value="item.id"
                :label="item.name"
              ></el-option>
            </el-select>
          </el-form-item>
        </template>

        <el-form-item label="生成数量" prop="count" v-if="!isEdit">
          <el-input-number v-model="form.count" :min="1" :max="100" :precision="0" />
        </el-form-item>

        <el-form-item label="快速模式限制次数" prop="fastMaxCount">
          <template #label>
            <el-tooltip class="box-item" effect="dark" content="输入-1为无限次数" placement="top">
              <el-button link type="danger">fast限制次数</el-button>
            </el-tooltip>
          </template>
          <el-input-number v-model="form.fastMaxCount" :min="1" :precision="0" />
        </el-form-item>

        <el-form-item label="relax模式限制次数" prop="relaxMaxCount">
          <template #label>
            <el-tooltip class="box-item" effect="dark" content="输入-1为无限次数" placement="top">
              <!-- <span>relax模式限制次数</span> -->
              <el-button link type="danger">relax限制次数</el-button>
            </el-tooltip>
          </template>
          <el-input-number v-model="form.relaxMaxCount" :min="-1" :precision="0" />
        </el-form-item>

        <el-form-item label="使用天数" prop="day">
          <el-input-number v-model="form.day" :min="1" :precision="0" />
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input :rows="3" type="textarea" v-model.trim="form.remark" placeholder="请输入备注" />
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button v-if="!form.isConsumption" type="primary" @click="submitForm" :loading="formLoading" >确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Index">
import {
  listApi,
  createApi,
  deleteApi,
  updateApi,
  listAllApi
} from "@/api/consumption.js";
import usePagination from "@/hooks/usePagination";
import { deepClone, generateRandomHex } from "@/utils";
import { ElMessage, dayjs } from "element-plus";
import { useRoute } from "vue-router";
import MAP, { getEnumLabel } from "@/enum/index.js";
import * as XLSX from "xlsx";
import { getAllMeal } from "@/views/account/helper/meal.js";

// const router = useRouter();,categoryMap
const { proxy } = getCurrentInstance();
const { pagination, total } = usePagination();
const route = useRoute();

const type = route.meta.type || 0;

const list = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const title = ref("");
const isEdit = computed(() => title.value === "修改");
const bactchUpdateInstance = ref(null);
const mealList = ref([]);

const currentParams = computed(() => {
  const obj = deepClone(unref(queryParams.value));
  const [stm, etm] = obj.date || [];
  if (stm) {
    obj.createTimeStart = dayjs(stm)
      .startOf("day")
      .format("YYYY-MM-DD HH:mm:ss");
  }
  if (etm) {
    obj.createTimeEnd = dayjs(etm)
      .endOf("day")
      .format("YYYY-MM-DD HH:mm:ss");
  }
  delete obj.date;
  return obj;
});

const data = reactive({
  form: {},
  queryParams: {
    type
  },
  rules: {
    key: [{ required: true, message: "续费码不能为空", trigger: "blur" }],
    type: [{ required: true, message: "套餐不能为空", trigger: "blur" }]
  },
  formLoading: false
});

const { queryParams, form, rules, formLoading } = toRefs(data);

// 批量更新操作
const batchUpdate = () => {
  bactchUpdateInstance.value.init(ids.value);
};

// 导出所选条件数据
const exportAll = async () => {
  loading.value = true;
  const response = [];
  try {
    const res = await listAllApi({
      ...currentParams.value
    });
    response.push(...res.rows);
  } catch (error) {}
  loading.value = false;
  if (response.length === 0) {
    ElMessage.warning("数据为空");
    return;
  }

  const keys = {
    key: "授权码",
    token: "token",
    pCount: "使用次数",
    type: "账号类型",
    createTime: "创建时间",
    channelId: "渠道id",
    guildId: "导航id",
    maxUser: "最多服务器数",
    remark: "备注"
  };
  const keysName = Object.keys(keys);
  const valuesName = keysName.map(key => keys[key]);
  const data = response.map(item => {
    return keysName.map(key => {
      if (key === "type") {
        return getEnumLabel(MAP.categoryMap, item[key]);
      }
      return item[key];
    });
  });
  data.unshift(valuesName);
  // const data = [
  //   ["姓名", "年龄", "城市"],
  //   ["John Doe", 30, "New York"],
  //   ["Jane Doe", 25, "San Francisco"],
  //   ["Bob Smith", 35, "Los Angeles"],
  // ];

  // 创建一个工作簿
  const workbook = XLSX.utils.book_new();

  // 创建一个工作表
  const worksheet = XLSX.utils.aoa_to_sheet(data);

  // 将工作表添加到工作簿
  XLSX.utils.book_append_sheet(workbook, worksheet, "数据");

  // 将工作簿转为二进制数据
  XLSX.writeFile(workbook, "用户列表.xlsx");

  // // 创建下载链接
  // const link = document.createElement("a");
  // link.href = window.URL.createObjectURL(excelBlob);
  // link.download = "用户列表.xlsx";

  // // 触发点击链接进行下载
  // link.click();

  // // 释放对象URL，防止内存泄漏
  // window.URL.revokeObjectURL(link.href);
};

// 删除操作
const deleteHandler = row => {
  proxy.$modal
    .confirm("是否确认删除数据项?")
    .then(function() {
      return deleteApi(row.key);
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};

// 批量删除
// 删除操作
const batchDelete = () => {
  proxy.$modal
    .confirm("是否批量删除数据项?请注意，删除之后将无法恢复")
    .then(function() {
      return deleteApi(ids.value.map(v => v.key).join(","));
    })
    .then(() => {
      getList();
      proxy.$modal.msgSuccess("删除成功");
    })
    .catch(() => {});
};
/** 多选框选中数据 */
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 查询角色列表 */
function getList() {
  loading.value = true;
  listApi({
    ...currentParams.value,
    pageNo: pagination.current,
    pageSize: pagination.size
  })
    .then(response => {
      list.value = response.rows;
      loading.value = false;
      total.value = response.total;
    })
    .finally(() => {
      loading.value = false;
    });
}
/** 搜索按钮操作 */
function handleQuery() {
  // pagination.current = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  queryParams.value.date = "";
  handleQuery();
}

/** 重置新增的表单以及其他数据  */
function reset() {
  proxy.resetForm("roleRef");
  form.value = {};
}

/** 添加角色 */
function handleAdd() {
  reset();
  form.value.key = generateRandomHex()
  form.value.islink = 0;
  form.value.count = 1;
  form.value.type = type || "";
  open.value = true;
  title.value = "添加";
}

/** 修改角色 */
async function handleUpdate(row) {
  reset();
  title.value = "修改";
  form.value = deepClone(unref(row));
  open.value = true;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["roleRef"].validate(async valid => {
    if (valid) {
      formLoading.value = true;
      try {
        if (title.value === "修改") {
          // 更新
          await updateApi(unref(form.value));
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        } else {
          // 保存
          if (form.value.count > 1) {
            form.value.key = "";
          }
          await createApi(unref(form.value));
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }
      } catch (error) {}
      formLoading.value = false;
    }
  });
}
/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/**
 *
 */
const mealChangeHandler = e => {
  const item = mealList.value.find(v => v.id === e);
  if (!item) return;
  form.value.fastMaxCount = item.fast;
  form.value.relaxMaxCount = item.relax;
  form.value.type = item.type;
  form.value.day = item.day;
};

getList();

watch(
  () => open.value,
  val => {
    if (val) {
      mealList.value = getAllMeal().map((v, i) => {
        return {
          ...v,
          id: i
        };
      });
    }
  },
  { immediate: true }
);
</script>

<style lang="scss" scoped>
.on-default {
  color: var(--el-color-primary);
}

.on-success {
  color: var(--el-color-success);
}

.on-error {
  color: var(--el-color-error);
}
</style>
